package com.ns.school.service.base;

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ns.school.common.base.BaseClass;
import com.ns.school.common.base.BaseVO;
import com.ns.school.common.constant.StaticVarY;
import com.ns.school.common.utils.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * 基本业务层
 *
 * @author Spark
 */
public class BaseService extends BaseClass {

    protected Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 事务回滚
     */
    protected boolean transactionRollBack() {
        try {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("Transaction Rollback Successful");
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 事务回滚
     */
    protected boolean transactionRollBack(String msg) {
        try {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("Transaction Rollback Successful:{}", msg);
            return true;
        } catch (Exception e) {
            log.info(e.getMessage());
            return false;
        }
    }

    protected static JSONObject getWeChatMessage(String value, String color) {
        JSONObject json = new JSONObject();
        if (StrUtil.isEmpty(color)) {
            color = "#0044BB";// 默认蓝色文字
        }
        json.put("color", color);
        json.put("value", value);
        return json;
    }

    /**
     * 判断是否是本地or测试环境
     *
     * @return
     */
    protected static boolean isLocalTestProfile() {
        return "dev".equals(StaticVarY.profile) || "test".equals(StaticVarY.profile);
    }

    /**
     * 判断是否是本地环境
     *
     * @return
     */
    protected static boolean isLocalProfile() {
        return "dev".equals(StaticVarY.profile);
    }

    /**
     * 判断是否是测试环境
     *
     * @return
     */
    protected static boolean isTestProfile() {
        return "test".equals(StaticVarY.profile);
    }

    /**
     * 获取当前环境
     *
     * @return
     */
    protected static String getProfile() {
        return StaticVarY.profile;
    }

    /**
     * 休息会
     */
    protected void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }

    protected void startPage(BaseVO entity) {
        PageHelper.startPage(entity.getPage(), entity.getLimit());
    }

    protected void startPage(int page, int size) {
        PageHelper.startPage(page, size);
    }
}
